/*
 * ==================================================
 * 项目开发者：JerryStark
 * 开发者Email：4771007@qq.com
 * 开发者QQ:4771007
 * 开发范围：web，wap，android,ios,osx or win or linux 应用
 * ==================================================
 */
package lottery;

import Conter.Config;
import RTPower.RTMysql;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 静态类记录抓取的全部数据
 * <br>记录所有的数据
 *
 * @author jerry
 */
public class ResultData {

    /**
     * 用来记录所有的数据
     * <br>[game_tag][orderid]
     */
    public static JsonObject AllData = new JsonObject();

    /**
     * 单一顺序的线程池
     * <br>排队执行mysql任务
     */
    public static ExecutorService MysqlExecutor = Executors.newSingleThreadExecutor();

    /**
     * 保存数据到全局变量
     *
     * @param game_tag
     * @param one_data
     */
    public static void Save(String game_tag, JsonObject one_data) {

        if (one_data.entrySet().isEmpty()) {
            return;
        }
        //单线程池执行mysql的检测和写出
        MysqlExecutor.execute(new Runnable() {
            @Override
            public void run() {
                //数据存在则不执行写出变量和mysql处理

                //检查传入的数据是否在变量里存在,存在则退出
                if (AllData.has(game_tag)) {
                    JsonObject scandata = AllData.getAsJsonObject(game_tag);
                    if (scandata.has(one_data.get("orderid").getAsString())) {
                        //tag存在 id 存在,则终止
                        return;
                    }
                }

                //如果设置了URL传输,则把数据传送到指定url一次
                
                //检查并处理写出数据库
                MysqlSave(game_tag, one_data);

                //写出全局变量一次
                JsonObject game_json = new JsonObject();
                game_json.add(one_data.get("orderid").getAsString(), one_data);
                AllData.add(game_tag, game_json);
            }
        });

    }

    /**
     * 处理mysql 的存储
     * <br>按照配置文件配置
     *
     * @param game_tag
     * @param one_data
     */
    private static void MysqlSave(String game_tag, JsonObject one_data) {
        one_data.addProperty("tag", game_tag);
        //先读取mysql的配置
        JsonObject mysqlc = Config.MysqlConfig;

        String mysql_status = mysqlc.get("status").getAsString();
        //如果配置是关闭mysql存储的就停止

        if (!mysql_status.equals("start")) {
            return;
        }

        System.err.println(game_tag + ":开始准备存储进mysql");
        //
        RTMysql mysqlrs = new RTMysql();

        //遍历mysql的键值对应的字符串
        String mysql_keyString = "";

        String mysql_valuesString = "";

        /**
         * 查询条件
         */
        String mysql_selsct = "";
        mysql_selsct = "select * from " + mysqlc.get("table_name").getAsString();
        mysql_selsct += " where ";

        JsonObject keys_conf = mysqlc.getAsJsonObject("keys");
        for (Map.Entry<String, JsonElement> en : keys_conf.entrySet()) {
            String key = en.getKey();
            String value = en.getValue().getAsString();

            mysql_keyString += key + ",";
            //检查key师傅存在,在就替换c成变量里的否则还是原值
            if (one_data.has(value)) {
                value = one_data.get(value).getAsString();
            }
            mysql_valuesString += "'" + value + "',";

            mysql_selsct += " " + key + "='" + value + "' and";
        }

        //删除最后一个点
        mysql_keyString = mysql_keyString.substring(0, mysql_keyString.length() - 1);
        mysql_valuesString = mysql_valuesString.substring(0, mysql_valuesString.length() - 1);
        mysql_selsct = mysql_selsct.substring(0, mysql_selsct.length() - 3);
        //数据存在则不写出

        ResultSet select_rs = mysqlrs.Select(mysql_selsct + ";");

        try {
            select_rs.last();
            System.err.println("查询:" + select_rs.getRow());

            //如果查询数据=0才写出
            if (select_rs.getRow() == 0) {
                //组装mysql语句
                String mysqlString = "";

                mysqlString += "insert into " + mysqlc.get("table_name").getAsString();
                mysqlString += " (" + mysql_keyString + ") ";
                mysqlString += "values";
                mysqlString += " (" + mysql_valuesString + ");";

                int back_rs = mysqlrs.Insert(mysqlString);

                System.err.println("插入数据结果:" + back_rs);
            }
        } catch (SQLException ex) {
            Logger.getLogger(ResultData.class.getName()).log(Level.SEVERE, null, ex);
        }

        mysqlrs.close();

    }

}
